/**
 * Created by Tuffy on 16/1/18.
 */
'use strict';

angular.module('starter.controllers')
.controller('MsgCtrl', ['$scope', '$rootScope', '$timeout', '$ionicModal', '$ionicLoading','$cordovaToast', 'MessageService','$filter',
    function($scope, $rootScope, $timeout,$ionicModal, $ionicLoading,$cordovaToast, MessageService,$filter) {

    $scope.tabs = [{name: '未读', readStatus: 1}, {name: '已读', readStatus: 2}];

    $scope.active = 0;

    $scope.onTabChange = function(index, readStatus){
        $scope.msg.readStatus = readStatus;
        $scope.active = index;
        $scope.msg.refresh();
    };

    /**
     * msg
     */
    $scope.msg ={
        readStatus: 1,
        search: {
            value:'',
            filter:{},
            doAct:function(){
                if(this.timer){
                    $timeout.cancel(this.timer);
                }
                this.timer = $timeout(function(){
                    $scope.msg.page.pageNum = 1;
                    $scope.msg.data = [];
                    $scope.msg.loadData();
                },500);
            }
        },
        page: {
            pageNum:0,
            pageSize:10,
            total:200
        },
        loaded:false,
        data:[],
        loadData:function(okFunc){
            var _this = this,
                params = {
                    readStatus: _this.readStatus,
                    beginDate:_this.lastId,
                    pageSize:_this.page.pageSize
                };
            _this.loaded = false;
            for(var key in _this.search.filter){
                params[key] = _this.search.filter[key];
            }
            MessageService.getAll(params)
                .success(function(res){
                    if(res.success){
                        if(typeof (okFunc) == 'function'){
                            okFunc();
                        }
                        var _data = res.attribute.rows;
                        if(!_data || _data.length<=0){
                            _this.moreDataCanBeLoaded = false;
                            $cordovaToast.showShortBottom('已加载到尾页');
                            return;
                        }
                        _this.data = _this.data.concat(_data);
                    }else{
                        _this.moreDataCanBeLoaded = false;
                        console.log('加载失败');
                    }
                }).error(function(error){
                _this.moreDataCanBeLoaded = false;
                console.log(error);
            }).finally(function(){
                _this.loaded = true;
                if(_this.data.length<=0){
                    _this.moreDataCanBeLoaded = false;
                }
                $scope.$broadcast('scroll.refreshComplete');
                $scope.$broadcast('scroll.infiniteScrollComplete');
            });
        },
        moreDataCanBeLoaded:false,
        loadMore:function(){
            this.page.pageNum++;
            this.lastId = this.data.length>0 ? $filter('date')(this.data[this.data.length-1].updateTime,'yyyy-MM-dd HH:mm:ss') : 0;
            this.loadData();
        },
        refresh:function(){
            var _this = this;
            _this.lastId = '';
            _this.page.pageNum = 1;
            _this.moreDataCanBeLoaded = true;
            _this.loadData(function(){
                _this.data = [];
            });
        },
        // 标记已读
        markRead: function(item) {
            var that = this;
            MessageService.markRead({id: item.id})
                .success(function(res) {
                    if (res.success) {
                        $cordovaToast.showShortBottom('标记成功');
                    } else {
                        $cordovaToast.showShortBottom(res.errorMsg);
                    }
                })
                .error(function(error) {
                    $cordovaToast.showShortBottom('标记出错');
                })
            .finally(function() {
                that.refresh();
            })
        },
        // 删除已读
        deleteRead: function(item) {
            var that = this;
            MessageService.deleteRead({id: item.id})
                .success(function(res) {
                    if (res.success) {
                        $cordovaToast.showShortBottom('删除成功');
                    } else {
                        $cordovaToast.showShortBottom(res.errorMsg);
                    }
                })
                .error(function(error) {
                    $cordovaToast.showShortBottom('删除出错');
                })
            .finally(function() {
                that.refresh();
            })
        }
    } ;

    $rootScope.$on('msg-list-open', function () {
        if($scope.msg.data.length<=0){
            $scope.msg.moreDataCanBeLoaded = true;
            $scope.msg.refresh();
        }
    });
}])
.service('MessageService',['CrmHttp','$rootScope',function(CrmHttp,$rootScope){
    var url = '/crm/msg/';
    return {
        /**
         * 获取消息数据数据
         * @param params
         * @returns {*}
         */
        getAll: function (params) {
            var act = 'read-status';
            params['userId'] = $rootScope.localStorageObj.userId;
            return CrmHttp.post(url + act, params);
        },
        markRead: function(params) {
            var act = 'read';
            // params['userId'] = $rootScope.localStorageObj.userId;
            return CrmHttp.post(url + act, params);
        },
        deleteRead: function(params) {
            var act = 'delete';
            // params['userId'] = $rootScope.localStorageObj.userId;
            return CrmHttp.post(url + act, params);
        }
    };
}]);